package com.inossem.warehousestorage_inossem.adapter.up_frame;

import android.app.Dialog;
import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.inossem.utils.base.ArithUtils;
import com.inossem.utils.base.RegexUtils;
import com.inossem.utils.base.Utils;
import com.inossem.utils.listener.NoDoubleClickListener;
import com.inossem.warehousestorage_inossem.R;
import com.inossem.warehousestorage_inossem.activity.up_frame.UpFrameItemActivity;
import com.inossem.warehousestorage_inossem.bean.storage.StorageManageRespBean;
import com.inossem.warehousestorage_inossem.bean.up_frame.UpFrameOverviewBean;
import com.inossem.warehousestorage_inossem.bean.up_frame.UpFrameValidBean;
import com.inossem.warehousestorage_inossem.constant.RequestConstant;
import com.inossem.warehousestorage_inossem.dialog.DialogUtils;
import com.inossem.warehousestorage_inossem.listener.GsonBeanListener;
import com.inossem.warehousestorage_inossem.request.up_frame.UpFrameOverviewRequest;
import com.inossem.warehousestorage_inossem.utils.QRCodeEditTextWatcher;
import com.zhy.android.percent.support.PercentRelativeLayout;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;


/**
 * Created by cjz on 2017/6/6.
 */

public class UpFrameItemAdapter extends BaseAdapter {

    private Context mContext;

    private UpFrameOverviewBean.DataBean.MaterielListBean mBean;

    private List<UpFrameOverviewBean.DataBean.MaterielListBean.PositionListBean> positionList;

    private LayoutInflater inflater;

    private EditText positionNumber, number;

    private PercentRelativeLayout hideLayout;

    private String mUnit, lgnum, mPosition;

    private Button add;

    private TextView speicalInventoryDescription, specialInventoryFlag, materielCode, specialInventoryCode, materielDescription, serial, notUpFrameNumber, showAndHide;

    private UpFrameItemActivity.UpFrameItemListener mUpFrameItemListener;

    public UpFrameItemAdapter(Context context, UpFrameOverviewBean.DataBean.MaterielListBean bean, String lgnum, String position, UpFrameItemActivity.UpFrameItemListener upFrameItemListener) {
        mContext = context;
        mBean = bean;
        positionList = bean.getPositionList() == null ? new ArrayList<>() : bean.getPositionList();
        inflater = LayoutInflater.from(context);
        this.lgnum = lgnum;
        mUnit = bean.getUnit();
        mPosition = position;
        mUpFrameItemListener = upFrameItemListener;
    }

    @Override
    public int getCount() {
        return positionList.size() + 1;
    }

    @Override
    public Object getItem(int position) {
        return positionList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (position == 0) {
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.view_up_frame_item_list_first_item, null);
                this.speicalInventoryDescription = (TextView) convertView.findViewById(R.id.speicalInventoryDescription);
                this.specialInventoryFlag = (TextView) convertView.findViewById(R.id.specialInventoryFlag);
                this.materielCode = (TextView) convertView.findViewById(R.id.materielCode);
                this.specialInventoryCode = (TextView) convertView.findViewById(R.id.specialInventoryCode);
                this.materielDescription = (TextView) convertView.findViewById(R.id.materielDescription);
                this.serial = (TextView) convertView.findViewById(R.id.serial);
                this.notUpFrameNumber = (TextView) convertView.findViewById(R.id.notUpFrameNumber);
                this.positionNumber = (EditText) convertView.findViewById(R.id.position);
                number = (EditText) convertView.findViewById(R.id.number);
                add = (Button) convertView.findViewById(R.id.add);
                this.speicalInventoryDescription.setText(mBean.getSpeicalInventoryDescription());
                this.specialInventoryFlag.setText(mBean.getSpecialInventoryFlag());
                this.materielCode.setText(mBean.getMaterielCode());
                this.specialInventoryCode.setText(mBean.getSpecialInventoryCode());
                this.materielDescription.setText(mBean.getMaterielDescription());
                this.serial.setText(mBean.getSerial());
                this.notUpFrameNumber.setText(mBean.getNotUpFrameNumber());
                positionNumber.setText(mPosition);
                //展开按钮,如果特殊标识为空，则展出按钮都不用显示
                hideLayout = (PercentRelativeLayout) convertView.findViewById(R.id.hideLayout);
                showAndHide = (TextView) convertView.findViewById(R.id.showAndHide);
                if (TextUtils.isEmpty(mBean.getSpecialInventoryFlag())) {
                    showAndHide.setVisibility(View.GONE);
                } else {
                    showAndHide.setOnClickListener((View v) -> {
                        if (hideLayout.getVisibility() == View.GONE) {
                            hideLayout.setVisibility(View.VISIBLE);
                            ((TextView) v).setText(mContext.getResources().getString(R.string.common_hide_information));
                        } else if (hideLayout.getVisibility() == View.VISIBLE) {
                            hideLayout.setVisibility(View.GONE);
                            ((TextView) v).setText(mContext.getResources().getString(R.string.common_show_information));
                        }
                    });
                }
                this.positionNumber.addTextChangedListener(new QRCodeEditTextWatcher(this.positionNumber, true) {
                    @Override
                    public void onScan(String text) {
                        number.requestFocusFromTouch();
                    }
                });
                add.setOnClickListener(new NoDoubleClickListener() {
                    @Override
                    public void onNoDoubleClick(View v) {
                        if (TextUtils.isEmpty(positionNumber.getText().toString()) || TextUtils.isEmpty(number.getText().toString())) {
                            Utils.middleToast(mContext, "仓位信息和数量不可以为空");
                            return;
                        }
                        if (hasPositionNumber(positionNumber.getText().toString(), positionList)) {
                            Utils.middleToast(mContext, "该仓位已添加,请长按删除后重新添加");
                            return;
                        }
                        if (!RegexUtils.checkDecimal(number.getText().toString()) || Double.parseDouble(number.getText().toString()) <= 0) {
                            Utils.middleToast(mContext, "本次上架数量不合法");
                            return;
                        }
                        if (Double.parseDouble(number.getText().toString()) > getSurplus(Double.parseDouble(mBean.getNotUpFrameNumber()), positionList)) {
                            Utils.middleToast(mContext, mContext.getResources().getString(R.string.activity_up_frame_item_up_prompt));
                            return;
                        }
                        UpFrameValidBean params = new UpFrameValidBean();
                        params.setLgnum(lgnum);
                        params.setReceivePosition(positionNumber.getText().toString());
                        UpFrameOverviewRequest.valid(mContext, params, new GsonBeanListener<StorageManageRespBean>() {
                            @Override
                            public void onSuccess(StorageManageRespBean bean) {
                                //判断校验
                                if (bean.getData().getCode().equals(RequestConstant.BEAN_CODE_SUCCESS)) {
                                    UpFrameOverviewBean.DataBean.MaterielListBean.PositionListBean positionItem = new UpFrameOverviewBean.DataBean.MaterielListBean.PositionListBean();
                                    positionItem.setPosition(positionNumber.getText().toString());
                                    positionItem.setNumber(number.getText().toString());
                                    positionItem.setUnit(mUnit);
                                    positionItem.setId(UUID.randomUUID().toString());
                                    Utils.closeSoftKeyboard(mContext, positionNumber);
                                    mUpFrameItemListener.onNoDoubleClickListener(positionItem);
                                } else {
                                    Utils.middleToast(mContext, mContext.getResources().getString(R.string.activity_storage_manage_novalid_prompt));
                                }
                            }
                        });
                    }
                });
            }
        } else {
            UpFrameOverviewBean.DataBean.MaterielListBean.PositionListBean item = positionList.get(position - 1);
            ViewHolder viewHolder;
            if (convertView == null || (convertView != null && convertView.getTag() == null)) {
                convertView = inflater.inflate(R.layout.view_up_frame_item_list, null);
                viewHolder = new ViewHolder();
                //初始化控件
                initView(viewHolder, convertView);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            //初始化数据
            initData(mContext, viewHolder, convertView, item);
        }
        return convertView;
    }

    private void initView(ViewHolder viewHolder, View view) {
        viewHolder.postion = (TextView) view.findViewById(R.id.postion);
        viewHolder.number = (TextView) view.findViewById(R.id.number);
    }

    private void initData(Context context, ViewHolder viewHolder, View view, UpFrameOverviewBean.DataBean.MaterielListBean.PositionListBean item) {
        viewHolder.postion.setText(item.getPosition());
        viewHolder.number.setText(item.getNumber() + item.getUnit());
        //事件处理
        view.setOnLongClickListener((View v) -> {
            DialogUtils.getConfirmDialog(mContext, "确认要删除 ", new DialogUtils.ConfirmDialogListener() {
                @Override
                public void onConfirm(Dialog dialog) {
                    dialog.cancel();
                    mUpFrameItemListener.onDeletePositionNumber(item.getId());
                }
            }).show();
            return true;
        });
    }

    private class ViewHolder {
        private TextView postion, number;
    }

    private Double getSurplus(Double total, List<UpFrameOverviewBean.DataBean.MaterielListBean.PositionListBean> positionList) {
        Double result = total;
        if (positionList != null && !positionList.isEmpty()) {
            for (int i = 0; i < positionList.size(); i++) {
                UpFrameOverviewBean.DataBean.MaterielListBean.PositionListBean positionItem = positionList.get(i);
                Double number = Double.parseDouble(positionItem.getNumber());
                result = ArithUtils.sub(result, number);
            }
        }
        return result;
    }

    private boolean hasPositionNumber(String positionNumber, List<UpFrameOverviewBean.DataBean.MaterielListBean.PositionListBean> positionList) {
        if (positionList != null && !positionList.isEmpty()) {
            for (int i = 0; i < positionList.size(); i++) {
                UpFrameOverviewBean.DataBean.MaterielListBean.PositionListBean positionItem = positionList.get(i);
                if (positionItem.getPosition().equalsIgnoreCase(positionNumber)) {
                    return true;
                }
            }
        }
        return false;
    }
}
